package com.ambulance.project.biz.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.ambulance.common.exception.CustomException;
import com.ambulance.framework.MyRedisTemplate;
import com.ambulance.framework.manager.AsyncManager;
import com.ambulance.framework.redis.RedisCache;
import com.ambulance.framework.task.HdTask;
import com.ambulance.project.biz.dto.HsDto;
import com.ambulance.project.biz.dto.PlatUserListDto;
import com.ambulance.project.biz.dto.admin.AdminStatisticsDto;
import com.ambulance.project.biz.dto.admin.ResourceDto;
import com.ambulance.project.biz.dto.pad.CarDto;
import com.ambulance.project.biz.dto.pad.LoginResult;
import com.ambulance.project.biz.dto.web.CarHDInfo;
import com.ambulance.project.biz.dto.web.ReportDto;
import com.ambulance.project.biz.dto.web.WebCarDto;
import com.ambulance.project.biz.entity.Class;
import com.ambulance.project.biz.entity.*;
import com.ambulance.project.biz.enums.Role;
import com.ambulance.project.biz.mapper.MyCustomerMapper;
import com.ambulance.project.biz.service.*;
import com.ambulance.project.biz.util.ALiSms;
import com.ambulance.project.manager.domain.BizCardevice;
import com.ambulance.project.manager.domain.BizDispatch;
import com.ambulance.project.manager.domain.BizHospital;
import com.ambulance.project.manager.domain.BizTravelLog;
import com.ambulance.project.manager.mapper.BizDispatchMapper;
import com.ambulance.project.manager.service.IBizCardeviceService;
import com.ambulance.project.manager.service.IBizHospitalService;
import com.ambulance.project.manager.service.impl.BizTravelLogServiceImpl;
import com.ambulance.project.manager.utils.MgtCommonUtil;
import com.ambulance.utils.CommonUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/***
 *  @description
 *  @author zhao
 *  @date: 2020/4/27
 *  @version: v1.0
 */
@Service(value = "myCustomerService")
public class MyCustomerServiceImpl implements MyCustomerService {

    @Autowired
    private DispatchService dispatchService;

    @Autowired
    private CarService carService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private ClassService classService;

    @Autowired
    private PatientService patientService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private DispatchNoticeService dispatchNoticeService;


    @Autowired
    private DispatchCaseService dispatchCaseService;

    @Autowired
    private TradeService tradeService;
    @Autowired
    private CarChannelService carChannelService;
    @Autowired
    private HdTask hdTask;
    @Autowired
    private MyCustomerMapper myCustomerMapper;
    @Autowired
    private StatisticsService statisticsService;
    @Autowired
    private MgtCommonUtil mgtCommonUtil;
    @Autowired
    private EcgDataInfoService ecgDataInfoService;
    @Autowired
    private BizTravelLogServiceImpl bizTravelLogService;
    @Autowired
    private NurseService nurseService;
    @Autowired
    private BizDispatchMapper bizDispatchMapper;
    @Autowired
    private IBizHospitalService bizHospitalService;
    @Autowired
    private IBizCardeviceService bizCardeviceService;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private CarDeviceService carDeviceService;

    /**
     * 释放车辆资源
     */
    private void releaseCarResource(Integer carID, Integer driverID, String driverName, LocalDateTime lastTime) {
        Car car = new Car();
        car.setCarID(carID);
        car.setStatus(0);
        car.setLastDispatchDriverid(driverID);
        car.setLastDispatchTime(lastTime);
        car.setLastDispatchDriverName(driverName);
        carService.updateById(car);
    }

    /**
     * 释放班组资源
     *
     * @param classID
     */
    private void releaseClassResource(Integer classID) {
        Class aClass = new Class();
        aClass.setClassID(classID);
        aClass.setCarStatus(0);
        classService.updateById(aClass);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void releaseSource(Integer dispatchID, Integer isOver) {
        Dispatch dispatch = dispatchService.getById(dispatchID);
        if (CommonUtils.checkNull(dispatch)) {
            throw new CustomException("调度不存在");
        }
        // 调度校验
        /*if (!dispatch.getUid().equals(uid)) {
            throw new CustomException("该调度员不能撤销其他调度员的调度任务");
        }*/
        if (dispatch.getIsOver().equals(1)) {
            throw new CustomException("调度已结束");
        }

        Car car = carService.getById(dispatch.getCarID());
        if (CommonUtils.checkNull(car)) {
            throw new CustomException("车辆信息不存在");
        }
        Driver driver = driverService.getById(dispatch.getDriverID());
        Class classInfo = classService.getById(dispatch.getClassID());
        if (CommonUtils.checkNull(classInfo)) {
            throw new CustomException("班组不存在");
        }

        // 释放redis资源


        //车辆状态
        releaseCarResource(car.getCarID(), dispatch.getDriverID(), driver.getName(), dispatch.getDispatchTime());

        //班组状态
        releaseClassResource(dispatch.getClassID());

        releaseDispatchCarDeviceInfo(dispatchID, car);

        //司机状态
        Driver driver1 = new Driver();
        driver1.setDriverID(driver.getDriverID());
        driver1.setOnDutyStatus(1);
        driverService.updateById(driver1);

        //调度状态
        Dispatch dispatch1 = new Dispatch();
        dispatch1.setDispatchID(dispatch.getDispatchID());
        dispatch1.setIsOver(isOver);
        dispatchService.updateById(dispatch1);
    }

    @Override
    public void cancelCar(Integer dispatchID, String reason) {


        Dispatch dispatch = dispatchService.getOne(new QueryWrapper<Dispatch>().eq("dispatchID", dispatchID));
        if (CommonUtils.checkNull(dispatch)) {
            throw new CustomException("调度不存在");
        }
        // 修改状态

        dispatch.setCancelTime(LocalDateTime.now());
        dispatch.setCancel(1);
        dispatch.setCancelReason(reason);
        dispatch.setIsOver(2);

        final boolean b = dispatchService.updateById(dispatch);

        //修改调度通知
        QueryWrapper<DispatchNotice> noticeQueryWrapper = new QueryWrapper<>();
        noticeQueryWrapper.eq("dispatchID", dispatchID);
        DispatchNotice notice = new DispatchNotice();
        notice.setStatus(0);
        dispatchNoticeService.update(notice, noticeQueryWrapper);

        // todo 发送取消派车通知短信

        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
//                给医生发短信
                final Doctor doctorServiceById = doctorService.getById(dispatch.getDoctorID());
                final SendSmsResponse sms_1932373241 = ALiSms.sendSms(doctorServiceById.getPhone(), "SMS_194050527", "{\"vin\":\"" + dispatch.getVin() + "\"}");
            }
        });

        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
//                给护士发短信
                final Nurse nurseServiceById = nurseService.getById(dispatch.getNurseID());
                final SendSmsResponse sms_1932373241 = ALiSms.sendSms(nurseServiceById.getPhone(), "SMS_194050527", "{\"vin\":\"" + dispatch.getVin() + "\"}");
            }
        });

        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
//                给司机发短信
                final Driver driverServiceById = driverService.getById(dispatch.getDriverID());
                final SendSmsResponse sms_1932373241 = ALiSms.sendSms(driverServiceById.getPhone(), "SMS_194050527", "{\"vin\":\"" + dispatch.getVin() + "\"}");
            }
        });
        // 释放资源
        releaseSource(dispatchID,2);

    }

    /**
     * 调度派车逻辑
     *
     * @param patientID
     * @param driverID
     * @param classID
     * @param carID
     * @param uid
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> scheduleCar(Integer patientID, Integer driverID, Integer classID, Integer carID, Integer uid) {

        Driver driver = driverService.getById(driverID);
        Patient patient = patientService.getById(patientID);
        Class classInfo = classService.getById(classID);
        Car carInfo = carService.getById(carID);

        // 校验司机，患者，班组，车辆，是否已经被处理
        if (CommonUtils.checkNull(driver) || CommonUtils.checkNull(patient) || CommonUtils.checkNull(classInfo)
                || CommonUtils.checkNull(carInfo)) {
            throw new CustomException("传入参数有误");
        }
        if (driver.getStatus() == 2) {
            throw new CustomException(("司机已派出"));
        }
        if (carInfo.getStatus() == 2) {
            throw new CustomException(("车辆已派出"));
        }
        if (patient.getStatus() == 1) {
            throw new CustomException(("调度信息已处理"));
        }
        if (classInfo.getCarStatus() == 1) {
            throw new CustomException(("班组已出车"));
        }


        //User byId = userService.getById(uid);
        //if (CommonUtils.checkNull(byId)) {
        //  throw new CustomException(("传入医院标识有误"));
        //}
        Dispatch dispatch = new Dispatch();

        // 查询车辆绑定的设备信息
		final List<CarDevice> carDeviceList = carDeviceService.list(new QueryWrapper<CarDevice>().eq("carID", carID));
		String carDeviceIds = "";
		Integer flag = 0;
        if(!CommonUtils.checkNull(carDeviceList)){
			for (CarDevice item: carDeviceList) {
				carDeviceIds += item.getDeviceID() + ",";
				if(item.getType().equals("3")){
				    //飞利浦
                    dispatch.setHsStatus(1);
                }
                if(item.getType().equals("4")){
                    //汇声
                    dispatch.setHsStatus(2);
                }
			}
			carDeviceIds = carDeviceIds.trim().substring(0,carDeviceIds.length()-1);
		}
		Doctor doctor = doctorService.getById(classInfo.getDoctorID());
        // 调度记录
		dispatch.setCarDeviceId(carDeviceIds);
        dispatch.setDriverID(driverID);
        dispatch.setClassID(classID);
        dispatch.setCarID(carID);
        dispatch.setPatientID(patientID);
        dispatch.setVin(carInfo.getVin());
        // 设置调度的车辆类型
        dispatch.setCarType(carInfo.getType());
        //调度状态
        dispatch.setStatus(0);
        dispatch.setHospital(patient.getHospital());
        dispatch.setDoctorID(classInfo.getDoctorID());
        dispatch.setNurseID(classInfo.getNurseID());
        dispatch.setDoctorName(doctor.getName());
        dispatch.setPatientName(patient.getName());
        dispatch.setVin(carInfo.getVin());
        dispatch.setDispatchTime(LocalDateTime.now());
        dispatch.setDriverPhone(driver.getPhone());
        dispatch.setDriverName(driver.getName());
        dispatch.setDoctorPhone(doctor.getPhone());
        //接警时间
        dispatch.setReceiveHelpTime(patient.getReceiveNoticeTime());
        dispatch.setPatientCard(patient.getPatientCard());
        dispatch.setFlow(CommonUtils.getRandomString());
        dispatch.setUid(uid);

        //保存调度信息
        boolean save = dispatchService.save(dispatch);
        if (!save) {
            throw new CustomException();
        }
        // 判断是否为汇声设备
        if(!CommonUtils.checkNull(dispatch.getHsStatus()) && dispatch.getHsStatus().equals(2)){
            //                    汇声推流地址格式
//                    rtmp://47.92.143.196:1935/car_ + 调度id + /video1
            String rtmp = " rtmp://47.92.143.196:1935/car_" + dispatch.getDispatchID()  + "/video1";
            dispatch.setHsRtmp(rtmp);
            dispatchService.updateById(dispatch);
        }
        //调度通知
        DispatchNotice notice = new DispatchNotice();
        notice.setDispatchID(dispatch.getDispatchID());
        notice.setClassID(classID);
        notice.setDriverName(driver.getName());
        //病发地点
        notice.setPatientAddress(patient.getPatientLocal());
        notice.setPatientName(patient.getName());
        notice.setVin(carInfo.getVin());
        notice.setUid(uid);
        //生成调度通知
        createDispatchNotice(notice, classInfo);
        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
//                给司机发短信
          ALiSms.sendSms(driver.getPhone(), "SMS_194050525", "{\"vin\":\"" + dispatch.getVin() + "\"}");
            }
        });
        // 存入redis
        dispatchCarDeviceInfo(dispatch.getDispatchID(), carInfo);

        // 更新急救信息 车辆 司机 班组 对应状态 done
        patient.setStatus(1);
        patientService.updateById(patient);
        carInfo.setStatus(2);
        carInfo.setLastDispatchTime(LocalDateTime.now());
        carInfo.setLastDispatchDriverid(driver.getDriverID());
        carInfo.setLastDispatchDriverName(driver.getName());
        carService.updateById(carInfo);
        driver.setOnDutyStatus(2);
        driverService.updateById(driver);
        classInfo.setCarStatus(1);
        classService.updateById(classInfo);
        //生成派车记录日志
        final BizTravelLog bizTravelLog = new BizTravelLog();
        bizTravelLog.setCarID(new Long(carID));
        bizTravelLog.setOutDriverId(new Long(driverID));
        bizTravelLog.setOutCarTime(new Date(System.currentTimeMillis()));
        bizTravelLog.setOutDriverName(driver.getName());
        bizTravelLog.setDispathId(new Long(dispatch.getDispatchID()));
        bizTravelLogService.insertBizTravelLog(bizTravelLog);


        //生成调度病例基本信息
        DispatchCase dispatchCase = new DispatchCase();
        dispatchCase.setDoctorName(doctor.getName());
        dispatchCase.setCarID(dispatch.getCarID());
        //调度病例患者信息
        dispatchCase.setDispatchID(dispatch.getDispatchID());
        dispatchCase.setPatientId(patientID);
        dispatchCase.setPatientName(patient.getName());
        //患者住址
        dispatchCase.setPatientAddress(patient.getAddress());
        //病发地址
        dispatchCase.setPatientLocal(patient.getPatientLocal());
        dispatchCase.setPatientAge(patient.getAge());
        dispatchCase.setPatientSex(patient.getSex());
        dispatchCase.setPatientMobile(patient.getPhone());
        dispatchCase.setPatientId(patient.getPatientId());
        dispatchCase.setHospital(patient.getHospital());
        //病例状态
        dispatchCase.setCaseStatus(0);
        //车辆信息
        dispatchCase.setVin(carInfo.getVin());
        dispatchCase.setMajorCase(patient.getMajorCase());
        dispatchCase.setCheckResult(patient.getCheckResult());
        dispatchCase.setFlow(dispatch.getFlow());
        // 生成调度对账
        Trade trade = new Trade();
        trade.setFlow(dispatch.getFlow());
        trade.setDispatchID(dispatch.getDispatchID());
        trade.setUid(uid);
        tradeService.save(trade);

        boolean save2 = dispatchCaseService.save(dispatchCase);
        if (!save2) {
            throw new CustomException("系统异常");
        }
        Map<String, Object> rlt = Maps.newHashMap();
        rlt.put("notice", notice);
        rlt.put("dispatchID", dispatch.getDispatchID());
        return rlt;

    }

    @Override
    public CarDto getCarChannelDto(Integer carID) {
        CarDto carDto = new CarDto();

        Car car = carService.getById(carID);
        QueryWrapper<CarChannel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("termSn", car.getTermSn());
        List<CarChannel> carChannelList = carChannelService.list(queryWrapper);
        carDto.setCar(car);
        carDto.setChannelList(carChannelList);
        return carDto;
    }

    /***
     * 查询医院的车辆列表
     * @param uid
     * @return
     */
    @Override
    public List<WebCarDto> listCar(Long uid) {
        List<WebCarDto> webCarDtos = myCustomerMapper.selectWebCarDtoByUid(uid.intValue());

        List<WebCarDto> results = Lists.newArrayList();
        if (!CommonUtils.checkNull(webCarDtos) && !webCarDtos.isEmpty()) {
            for (WebCarDto webCarDto : webCarDtos) {
                fillContentOnWebCarDto(webCarDto);
                getCarDeviceInfo(webCarDto);
                results.add(webCarDto);
            }
            //车辆排序
            results.sort((x, y) -> Integer.compare(x.getOrdertStatus(), y.getOrdertStatus()));
        }
        return results;
    }

    private void getCarDeviceInfo(WebCarDto webCarDto){
        final BizCardevice bizCardevice = new BizCardevice();
        bizCardevice.setCarID(webCarDto.getCarID().longValue());
        final List<BizCardevice> bizCardevices = bizCardeviceService.selectBizCardeviceList(bizCardevice);
        if(!CommonUtils.checkNull(bizCardevices)){
            for (BizCardevice item: bizCardevices) {
                switch (item.getType()){
                    case 1:
                        webCarDto.setEcg(1);
                        break;
                    case 2:
                        webCarDto.setBr(1);
                        break;
                    case 3:
                    case 4:
                        webCarDto.setUltrasound(1);
                }
            }
        }
    }

    //通过
    private void fillContentOnWebCarDto(WebCarDto webCarDto) {
        //获取车辆的通道类别
        //QueryWrapper<CarChannel> wrapper = new QueryWrapper<>();
        //wrapper.eq("termSn",webCarDto.getTermSn());
        //List<CarChannel> carChannels = carChannelService.list(wrapper);
        //webCarDto.setChannelList(carChannels);
        //获取车辆的目的地
        QueryWrapper<Dispatch> dispatchQueryWrapper = new QueryWrapper<>();
        dispatchQueryWrapper.eq("carID", webCarDto.getCarID()).orderByDesc("receive_help_time").last("LIMIT 1");
        Dispatch one = dispatchService.getOne(dispatchQueryWrapper, false);

        //dispatchCaseService.getById()
        if (!CommonUtils.checkNull(one) && one.getIsOver() == 0) {
            webCarDto.setDispathID(one.getDispatchID());
            QueryWrapper<DispatchCase> caseQueryWrapper = new QueryWrapper<>();
            caseQueryWrapper.eq("dispatchID", one.getDispatchID());
            DispatchCase aCase = dispatchCaseService.getOne(caseQueryWrapper);
            webCarDto.setDispathCaseID(aCase.getDispatchCaseid());
            if (one.getStatus() < 4) {
                //未到达医院，则查询急救信息表
                webCarDto.setDestination(aCase.getPatientLocal());
                webCarDto.setOrdertStatus(2);
                CarHDInfo noAlarm = hdTask.getCarGpsInfoNoAlarm(webCarDto.getId());
                webCarDto.setLatitude(noAlarm.getLatitude());
                webCarDto.setLongitude(noAlarm.getLongitude());
            } else if (one.getStatus() == 8) {
                webCarDto.setOrdertStatus(3);
            } else {
                webCarDto.setDestination(aCase.getHospital());
                webCarDto.setOrdertStatus(1);
                CarHDInfo noAlarm = hdTask.getCarGpsInfoNoAlarm(webCarDto.getId());
                webCarDto.setLatitude(noAlarm.getLatitude());
                webCarDto.setLongitude(noAlarm.getLongitude());
            }
            webCarDto.setPatientLocal(aCase.getPatientLocal());
            webCarDto.setHospital(aCase.getHospital());
            final HsDto hsDto = new HsDto();
            hsDto.setHsRtmp(one.getHsRtmp());
            hsDto.setHsStatus(one.getHsStatus());
            webCarDto.setHsDto(hsDto);
        } else {
            webCarDto.setOrdertStatus(4);
        }
        // 设置经纬度


    }

    @Override
    public WebCarDto getWebCarDto(Integer carID) {
        WebCarDto webCarDto = myCustomerMapper.selectWebCarDtoByCarID(carID);
        fillContentOnWebCarDto(webCarDto);
        return webCarDto;
    }

    @Override
    public Dispatch getRecentDispatchByCarID(Integer carID) {
        QueryWrapper<Dispatch> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("carID", carID).orderByDesc("receive_help_time").last("LIMIT 1");
        Dispatch one = dispatchService.getOne(queryWrapper);
        if (CommonUtils.checkNull(one)) {
            throw new CustomException("调度不存在");
        }
        return one;
    }

    @Override
    public DispatchCase getDispatchCaseRecentByCar(Integer carID) {
        Dispatch byCarID = getRecentDispatchByCarID(carID);
        QueryWrapper<DispatchCase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dispatchID", byCarID.getDispatchID());
        DispatchCase dispatchCase = dispatchCaseService.getOne(queryWrapper);
        if (CommonUtils.checkNull(dispatchCase)) {
            throw new CustomException("调度不存在");
        }
        return dispatchCase;
    }

    //pad登陆
    @Override
    public LoginResult padLogIn(String code) {
        QueryWrapper<DispatchNotice> noticeQueryWrapper = new QueryWrapper<>();
        noticeQueryWrapper.eq("token", code).eq("status", 1);
        DispatchNotice noticeServiceOne = dispatchNoticeService.getOne(noticeQueryWrapper);
        if (CommonUtils.checkNull(noticeServiceOne)) {
            throw new CustomException("验证码不存在");
        }
        LoginResult loginResult = new LoginResult();
        if (noticeServiceOne.getType() == 1) {
            loginResult.setRole(Role.DOCTOR.name());
        } else {
            loginResult.setRole(Role.NURSE.name());
        }
        loginResult.setUserMark(noticeServiceOne.getUsrID());
        loginResult.setUserMark(noticeServiceOne.getUid());
        return loginResult;
    }

    @Override
    public EcgDataInfo getEcgData(Integer carID, Integer dispachID, String type) {
        QueryWrapper<EcgDataInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("car_iD", carID).eq("dispatch_iD", dispachID);
        EcgDataInfo one = ecgDataInfoService.getOne(queryWrapper);

        return one;
    }

    @Override
    public ResourceDto getResource(Integer uid) {
        final QueryWrapper<Dispatch> dispatchQueryWrapper = new QueryWrapper<>();
        dispatchQueryWrapper.eq("uid", uid).eq("is_over", 0);
        dispatchService.list(dispatchQueryWrapper).size();
        return null;
    }

    @Override
    public Map<String, AdminStatisticsDto> getCurrentMonthAndLastData() {
        Map<String, AdminStatisticsDto> rlt = Maps.newHashMap();
        LocalDate now = LocalDate.now();
        QueryWrapper<Statistics> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Statistics> queryWrapper2 = new QueryWrapper<>();

        //获取uid
        int uid = mgtCommonUtil.getMgtUserLoginResult().getUid();
        queryWrapper.eq("year", now.getYear()).eq("month", now.getMonth().getValue()).eq("uid", uid).orderByAsc("day");
        LocalDate lastMonth = now.minusMonths(1);
        queryWrapper2.eq("year", lastMonth.getYear()).eq("month", lastMonth.getMonth().getValue()).eq("uid", uid).orderByAsc("day");
        List<Statistics> list = statisticsService.list(queryWrapper);
        List<Statistics> list2 = statisticsService.list(queryWrapper2);
        AdminStatisticsDto currentMonth = new AdminStatisticsDto();
        AdminStatisticsDto currentMonth2 = new AdminStatisticsDto();
        insertValueFromBean(list, currentMonth);
        currentMonth.setMonth(now.getMonth().getValue());
        currentMonth.setYear(now.getYear());

        insertValueFromBean(list2, currentMonth2);
        currentMonth2.setMonth(lastMonth.getMonthValue());
        currentMonth2.setYear(lastMonth.getYear());


        rlt.put("current", currentMonth);
        rlt.put("last", currentMonth2);
        return rlt;
    }

    private AdminStatisticsDto insertValueFromBean(List<Statistics> list, AdminStatisticsDto adminStatisticsDto) {
        List<Integer> times = Lists.newArrayList();
        List<Integer> days = Lists.newArrayList();
        List<Long> onHelpTimes = Lists.newArrayList();
        List<Long> onCarTimes = Lists.newArrayList();

        for (Statistics item : list) {
            days.add(item.getDay());
            times.add(item.getTime());
            onHelpTimes.add(item.getAvgBaseHelp().longValue());
            onCarTimes.add(item.getAvgCar().longValue());
        }
        adminStatisticsDto.setDays(days);
        adminStatisticsDto.setOnHelpTime(onHelpTimes);
        adminStatisticsDto.setTimes(times);
        adminStatisticsDto.setOnCarTime(onCarTimes);
        return adminStatisticsDto;
    }

    // redis 将车辆设备和调度放入redis
    private void dispatchCarDeviceInfo(Integer dispatchId, Car car) {
        // 获取车辆设备
        BizCardevice cardevice = new BizCardevice();
        cardevice.setCarID(car.getCarID().longValue());
        List<BizCardevice> cardeviceList = bizCardeviceService.selectBizCardeviceList(cardevice);
        if (null != cardeviceList && !cardeviceList.isEmpty()) {


            String key = "dispatch_hash_" + dispatchId;
            String deviceDisPatchHaskKey="device_dispatch_hash:";
            for (BizCardevice item : cardeviceList) {
                Integer type = item.getType();
                String typeKey = "t_" + type;
                // 调度下，设备类型，设备序列号 映射
                myRedisTemplate.opsForHash().put(key,typeKey,item.getSerial());
                // 设备号和调度的映射
                myRedisTemplate.opsForHash().put(deviceDisPatchHaskKey,item.getSerial(),dispatchId + "");
            }
            myRedisTemplate.expire(key, 24, TimeUnit.HOURS);
        }

    }

    private void releaseDispatchCarDeviceInfo(Integer dispatchId, Car car) {
        // 获取车辆设备
        BizCardevice cardevice = new BizCardevice();
        cardevice.setCarID(car.getCarID().longValue());
        List<BizCardevice> cardeviceList = bizCardeviceService.selectBizCardeviceList(cardevice);
        if (null != cardeviceList && !cardeviceList.isEmpty()) {

            Map<String, String> map = Maps.newHashMap();
            for (BizCardevice item : cardeviceList) {
                Integer type = item.getType();
                map.put("t_" + type, item.getSerial());
            }
            redisCache.deleteObject("d_" + dispatchId);
        }

    }

    private void createDispatchNotice(DispatchNotice dispatchNotice, Class classInfo) {
        String token = CommonUtils.getRandomNumber();
        dispatchNotice.setToken(token);
        dispatchNotice.setType(1);
        dispatchNotice.setUsrID(classInfo.getDoctorID());
        dispatchNotice.setCreateAt(LocalDateTime.now());
        boolean save1 = dispatchNoticeService.save(dispatchNotice);
        if (!save1) {
            throw new CustomException();
        }

        String token1 = CommonUtils.getRandomNumber();
        dispatchNotice.setNoticeID(null);
        dispatchNotice.setToken(token1);
        dispatchNotice.setType(2);
        dispatchNotice.setUsrID(classInfo.getNurseID());
        boolean save2 = dispatchNoticeService.save(dispatchNotice);
        LocalDate.now().toString();
        if (!save2) {
            throw new CustomException();
        }


        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                //给护士发短信
                final Nurse nurseServiceById = nurseService.getById(classInfo.getNurseID());
                final SendSmsResponse sms_1932373241 = ALiSms.sendSms(nurseServiceById.getPhone(), "SMS_193237324", "{\"vin\":\"" + dispatchNotice.getVin() + "\",\"loginSign\":\"" + token1 + "\"}");
                System.out.println(sms_1932373241);
            }
        });

        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                final Doctor doctorServiceById = doctorService.getById(classInfo.getDoctorID());
                //给医生发短信
                final SendSmsResponse sms_193237324 = ALiSms.sendSms(doctorServiceById.getPhone(), "SMS_193237324", "{\"vin\":\"" + dispatchNotice.getVin() + "\",\"loginSign\":\"" + token + "\"}");
                System.out.println(sms_193237324);
            }
        });


    }

    /**
     * 获取调度报告
     *
     * @param dispatchId
     * @return
     */
    public ReportDto queryOneReport(Integer dispatchId) {
        final ReportDto reportDto = myCustomerMapper.queryOneReport(dispatchId);
        if (CommonUtils.checkNull(reportDto)) {
            throw new CustomException("暂无相关报告");
        }
        return reportDto;
    }

    @Override
    public List<BizDispatch> getDispatchList(BizDispatch dispatch) {
        List<BizDispatch> bizDispatches = bizDispatchMapper.selectBizDispatchList2(dispatch);
        return bizDispatches;
    }

    @Override
    public List<PlatUserListDto> getPlatUserListDto(Long[] ids) {

        List<PlatUserListDto> list = Lists.newArrayList();
        for (Long id : ids) {
            // todo 外援表主键从10000000
            if (id >= 10000000) {
                BizHospital bizHospital = bizHospitalService.selectBizHospitalById(id);
                PlatUserListDto platUserListDto = getPlatUserListDto(bizHospital);
                if (null != platUserListDto) {
                    list.add(platUserListDto);
                }
            } else {
                Doctor service = doctorService.getById(id);
                PlatUserListDto platUserListDto = getPlatUserListDto(service);
                if (null != platUserListDto) {
                    list.add(platUserListDto);
                }
            }
        }
        return list;
    }

    private PlatUserListDto getPlatUserListDto(BizHospital bizHospital) {
        if (null == bizHospital) {
            return null;
        }
        PlatUserListDto listDto = new PlatUserListDto();
        listDto.setDepart(bizHospital.getDepart());
        listDto.setHospital(bizHospital.getHospitalName());
        listDto.setUserMark(bizHospital.getHospitalID());
        listDto.setPhone(bizHospital.getRelationPhone());
        listDto.setUserName(bizHospital.getRelationName());

        return listDto;

    }

    private PlatUserListDto getPlatUserListDto(Doctor doctor) {
        if (null == doctor) {
            return null;
        }
        PlatUserListDto listDto = new PlatUserListDto();
        listDto.setDepart(doctor.getDepart());
        listDto.setHospital(doctor.getHospital());
        listDto.setUserMark(doctor.getDoctorID().longValue());
        listDto.setPhone(doctor.getPhone());
        listDto.setUserName(doctor.getName());
        return listDto;

    }


}
